/*
 * @Author: AskMeWhy
 * @Date:   2020-05-22 09:10:37
 * @Last Modified by: AskMeWhy
 * @Last Modified time: 2021-02-05 11:19:48
 */
const app = getApp();
// export const taskStateList = [
// { label: "待填报", value: "PENDING", state: "0", class: "state-review-pending" },
// { label: "待验收", value: "ACCEPTING", state: "1", class: "state-draft" },
// { label: "验收通过", value: "ACCEPTANCE", state: "2", class: "" },
// { label: "已完成", value: "COMPLETE", state: "3", class: "state-review-pass" },
// { label: "已关闭", value: "CLOSE", state: "4", class: "state-failed" },
// { label: "验收未通过", value: "REJECTED", state: "2", class: "state-review-fail" },
// ];
export const taskStateList = [
    // { label: "待开始", value: "ACCEPTING", state: "1", class: "state-draft" },
    {label: "已完成", value: "COMPLETE", state: "2", class: "state-review-pass"},
    {label: "进行中", value: "EXECUTING", state: "1", class: "state-review-pending"},
    {label: "全部", value: "ALL", state: "0", class: "state-All-pending"},
];
export const taskMixin = {
    data: {
        tableData: [],
        status: "",
        pageSize: 20,
        currentPage: 1,
        total: 0,
        taskStateList: taskStateList,
        isRefreshing: false,//是否下拉刷新状态
        isFinish: false,//是否加载完全部数据
        dataList: [],
        bageInfo: {"1": "", "2": "", "0": ""}

    },
    onLoad: function (options) {
        this.initData();
        // this.getTaskCount();
    },
    onRefresh() {
        console.log("这里是刷新======");
        this.initData();
    },
    async getTaskCount() {
        const response = await this.$_server("task/countByUser", {
            params: {
                assignee: "?assignee=" + app.user.userInfo.id,
            },
        });
        let {data} = response;
        if (data.code != 200) {
            return
        }
        let value = data.data;
        let bageInfo = this.data.bageInfo;
        bageInfo['1'] = value['unfinished_total'];
        bageInfo['2'] = value['finished_total'];
        bageInfo['0'] = value['total'];
        // console.log(data)
        this.setData({
            "bageInfo": bageInfo
        })
    },
    onPullDownRefresh() {
        this.initData().finally(() => {
            wx.stopPullDownRefresh();
        });
    },
    onReachBottom() {
        if (!this.data.isFinish) {
            let page = this.data.currentPage;
            this.initData(page + 1).finally(() => {
            });
        }
    },
    _scrollReachBottom() {
        if (!this.data.isFinish) {
            let page = this.data.currentPage;
            this.initData(page + 1).finally(() => {
            });
        }
    },
    getInitParams() {
        return {
            url: "task/list",
            data: {}
        };
    },
    async initData(page = 1) {

        if (!app.user.token) return false;
        // console.log("-------"+page)
        if (page == 1) {
            this.getTaskCount();
        }
        let {pageSize} = this.data;
        let otherParams = this.getInitParams();
        try {
            const response = await this.$_server(otherParams.url, {
                data: {
                    currentPage: page,
                    pageSize: 8,
                    ...otherParams.data,
                },
            });
            let {data} = response;
            if (data.code !== 200) {
                throw data;
            }
            let {data: list} = data;
            const tableData = this.buildTableData(list.records || []);

            tableData.forEach(element => {


                let createTime = element.source.createTime ?? "";
                let deadTime = element.source.endDate;
                // console.log(deadTime);
                if (!deadTime) {
                    deadTime = createTime
                }
                // console.log(deadTime);
                // //计算时间差
                var start_date = new Date().getTime() //new Date(createTime.replace(/-/g , "/"));
                var end_date = new Date(deadTime.replace(/-/g, "/"));
                var days = end_date.getTime() - start_date;
                var hour = parseInt(days / (1000 * 60 * 60));
                var day = parseInt(days / (1000 * 60 * 60 * 24));


                //赋值
                element.source.hour = hour
                element.source.day = day
                try {
                    element.source.endDate = deadTime.split(' ')[0];
                } catch (e) {
                }
                //判断颜色
                var bg_color = "";

                let status = element.source.status;

                // console.log(element.source.deleted,element.source);

                let deleted = element.source.deleted;
                if (deleted == true) {
                    bg_color = "#D4D4D4";
                } else {
                    //是否显示审批操作 按钮
                    if (element.source.category == "approval") {

                        let approvalStatus = element.source.approvalStatus;
                        element.source.approvalItem = 1;
                        if (status == 1) {
                            //进行中
                            if (hour < 0) {
                                //逾期
                                bg_color = "#FF8635";
                            } else {
                                bg_color = "#DD1818";
                            }
                            // console.log("相差的天数===="+hour);
                        } else if (status == 2) {
                            //已完成
                            if (approvalStatus == 2) {
                                //审批驳回
                                bg_color = "#CACACA";
                            } else {
                                //if(approvalStatus==1)
                                //审批通过
                                bg_color = "#65A65B";
                            }
                        } else {
                        }
                    } else {
                        element.source.approvalItem = 0;
                        if (status == 1) {
                            if (hour > 24) {
                                bg_color = "#01C690";

                            } else if (hour >= 0 && hour < 24) {
                                bg_color = "#16A1F6";
                            } else {
                                bg_color = "#FF8635";
                            }

                        } else if (status == 2) {
                            bg_color = "#09BB06";
                        }
                    }

                }


                element.source.bg_color = bg_color;


            });


            let _tableData = [];
            if (page === 1) {
                _tableData = tableData;
            }
                // else if(page === this.data.currentPage){
                //     _tableData = this.data.tableData.slice(0, this.data.tableData.length - this.data.pageSize).concat(tableData);
            // }
            else {
                _tableData = this.data.tableData.concat(tableData);
            }
            if (list.pages && page > list.pages) {
                page = list.pages
            }
            // console.log(_tableData);


            let total = data.data.total;
            let status = otherParams.data.status;
            let bageInfo = this.data.bageInfo;
            bageInfo[status] = total > 0 ? total : "";

            this.setData({
                currentPage: page,
                tableData: _tableData,
                status: otherParams.data.status,
                total: list.total || 0,
                // bageInfo:bageInfo,
                isRefreshing: false,//关闭下拉刷新
                isFinish: _tableData.length >= data.data.total, //全部加载完毕
                orgCategoryId: app.user.userInfo.orgCategoryId,
            });
        } catch (error) {
            console.log(error)
            this.loginFail()
        }
    },
    loginFail() {
        let bageInfo = {"1": "", "2": "", "0": ""}
        this.setData({
            currentPage: 1,
            tableData: [],
            total: 0,
            bageInfo: bageInfo,
            isRefreshing: false,//关闭下拉刷新
            isFinish: true
        });
    },
    buildTableData(list) {
        let res = [];
        if (list.length === 0) {
            return res;
        }
        const nowTime = +new Date();
        res = list.map(cur => {
            const endDate = cur.finishTime ? new Date(cur.finishTime) : "";
            let endClass = "";
            if (endDate) {
                endDate.setDate(endDate.getDate() + 1);
                endDate.setHours(0);
                endDate.setMinutes(0);
                endDate.setSeconds(0);
                endDate.setMilliseconds(0);
                let diff = endDate.getTime() - nowTime;
                endClass = diff > 0 && diff <= 1000 * 60 * 60 * 24 ? "red" : "";
            }
            // cur.name = "wy自定义流程12审批节点-aaa";
            return {
                id: cur.id || "",
                cover: "",
                // 任务名称
                name: cur.name || "",
                // 截至时间
                endTime: cur.finishTime || "",
                endClass: endClass,
                // 任务进度
                taskNum: cur.process || 0,
                // 是否展示完成填报
                // canEnd: cur.forwardNum && cur.forwardNum === 1,
                // readonly: !!cur.readOnly || (cur.forwardNum && cur.forwardNum > 1),
                canEnd: true,
                readonly: !!cur.readOnly,
                node: {
                    type: (cur.name || "").indexOf("经办") === -1 ? "REVIEW" : "RUN",
                },
                state: this.$key2Name(
                    {
                        type: cur.status + "",
                        key: "state",
                        list: this.data.taskStateList,
                    },
                    "obj"
                ),
                rejectDesc: cur.comment || "",
                source: cur,
            };
        });
        return res;
    },

    //绑定微信
    bindWxAction() {
        console.log("111");
    }


};
